﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EFTracingProvider;
using EFProviderWrapperToolkit;
using System.Diagnostics;

namespace MoneyManagerNET.DAL.Repository.EF4.SqlCe
{

    public class TrecableObjectContext : SqlCeModelContainer
    {

        public TrecableObjectContext()
            : this("name=SqlCeModelContainer")
        {
        }

        public TrecableObjectContext(string connectionString)
            : base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
                    connectionString,
                    "EFTracingProvider"
            ))
        {
            CommandExecuting += AppendToLog;

        }


        static TraceSource trace = new TraceSource("storage");

        #region Tracing Extensions

        private EFTracingConnection TracingConnection
        {
            get { return this.UnwrapConnection<EFTracingConnection>(); }
        }

        public event EventHandler<CommandExecutionEventArgs> CommandExecuting
        {
            add { this.TracingConnection.CommandExecuting += value; }
            remove { this.TracingConnection.CommandExecuting -= value; }
        }

        public event EventHandler<CommandExecutionEventArgs> CommandFinished
        {
            add { this.TracingConnection.CommandFinished += value; }
            remove { this.TracingConnection.CommandFinished -= value; }
        }

        public event EventHandler<CommandExecutionEventArgs> CommandFailed
        {
            add { this.TracingConnection.CommandFailed += value; }
            remove { this.TracingConnection.CommandFailed -= value; }
        }

        private void AppendToLog(object sender, CommandExecutionEventArgs e)
        {
            
            trace.TraceInformation(e.ToTraceString().TrimEnd());
            
            
        }


        #endregion
    }
}
